package org.springblade.modules.develop.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.develop.utils.FileUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("/code")
@Api(value = "代码生成", tags = "代码生成")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
@Slf4j
public class MyCodeController {
	/**
	 * 代码生成
	 */
	@PostMapping("/tpl/genCode")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "代码生成", notes = "")
	public R tplGenCode(@ApiParam(value = "参数", required = true) @RequestBody JSONObject params) {
		String currentNode= params.getString("currentNode");
		JSONObject buttonJSONObject= params.getJSONObject("button");
		String buttonValue=buttonJSONObject.getString("value");
		JSONObject configJSONObject=buttonJSONObject.getJSONObject("config");
		try {
			String templatePath=currentNode+"/"+buttonJSONObject.getString("value")+".txt";
			if("tpl".equals(buttonValue)){
				templatePath=configJSONObject.getString("tplPath");
			}
			System.out.println(templatePath);
			GroupTemplate gt = getGroupTemplate();
			Template t = gt.getTemplate(templatePath);
			t.fastBinding(configJSONObject);
			String code=t.render();
			return R.data(code);
		}catch (Exception e){
			log.error("出错：",e);
		}
		return R.fail("渲染失败");
	}

	public static String getTplPathPre() {
		return SpringUtil.getBean(Environment.class).getProperty("beetl.tpl.path");
	}

	public GroupTemplate getGroupTemplate() throws Exception {
		FileResourceLoader resourceLoader = new FileResourceLoader(getTplPathPre(), "utf-8");
//		Configuration cfg = Configuration.defaultConfiguration();
//		GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
		BeetlGroupUtilConfiguration cfg=new BeetlGroupUtilConfiguration();
		cfg.setResourceLoader(resourceLoader);
		Map<String, Object> functionPackages=new HashMap<>();
		functionPackages.put("sputil", new org.beetl.ext.spring.UtilsFunctionPackage());
		functionPackages.put("vueRender", new org.springblade.modules.develop.beetl.function.RenderFunction());
		cfg.setFunctionPackages(functionPackages);
		cfg.init();
		GroupTemplate gt = cfg.getGroupTemplate();
		return gt;
	}

	@GetMapping("/openFile")
	@ApiOperation(value = "2、打开文件", notes = "打开文件1", position = 2)
	public R openFile(String path){
		Process process = null;
		try{
			Runtime runtime = Runtime.getRuntime();
			process = runtime.exec("D:\\ys\\notepad\\notepad++.exe  "+path);
		}catch(Exception e){
			log.error("出错：",e);
		}
		return R.data("操作成功");
	}

	@GetMapping("/readFile")
	@ApiOperation(value = "读取文件", notes = "读取文件", position = 2)
	public R readFile(String path){
		try {
			return R.data(FileUtils.readFileToString(new File(path),"utf-8"));
		} catch (IOException e) {
			log.error("出错：",e);
		}
		return R.fail("操作失败");
	}

	@PostMapping("/createFile")
	@ApiOperation(value = "3、创建文件", notes = "创建文件", position = 3)
	public R createFile(String path,String code){
		FileUtils.createFile(path);
		FileUtils.writeToFile(path,code,false);
		return R.data("操作成功");
	}

	@GetMapping("getAllFileList")
	public R getAllFileList(String path){
		List<Map<String,Object>> fileNameList=new ArrayList<>();
		File[] fileResult= FileUtils.getFileListByFilePath(path);
		if(fileResult!=null){
			for(File file:fileResult){
				Map<String,Object> map=new HashMap<>();
				map.put("name", file.getName());
				map.put("path", file.getPath());
				map.put("isDirectory", file.isDirectory());
				fileNameList.add(map);
			}
		}
		return R.data(fileNameList);
	}
}
